package ru.dadle8.service.impl.db;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.Message;
import ru.dadle8.model.bot.BotConsts;
import ru.dadle8.model.db.Workout;
import ru.dadle8.repository.WorkoutRepository;
import ru.dadle8.service.api.db.WorkoutService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class WorkoutServiceImpl implements WorkoutService {
    private final WorkoutRepository workoutRepository;

    @Override
    public void fillWorkout(Message inMess) {
        Optional<Workout> workout = workoutRepository.findByMessageId(inMess.getForwardFromMessageId());
        workout.ifPresentOrElse(w -> {
            populateWorkout(w, inMess);
            workoutRepository.save(w);
        }, () -> {
            Workout wNew = new Workout();
            populateWorkout(wNew, inMess);
            workoutRepository.save(wNew);
        });
    }

    @Override
    public List<Workout> findWorkouts(String searchText) {
        String title = searchText.substring(0, Math.min(searchText.length(), 100));
        List<String> tags = List.of(searchText);
        return workoutRepository.findByTitleContainsIgnoreCaseOrTagsContainingIgnoreCase(title, tags);
    }

    @Override
    public Page<Workout> findAllWorkouts(int num) {
        return workoutRepository.findAll(PageRequest.of(num, 60));
    }

    protected void populateWorkout(Workout w, Message inMess) {
        String text = StringUtils.defaultIfEmpty(inMess.getText(), inMess.getCaption());

        List<String> rows = Arrays.stream(text.split(BotConsts.NEW_LINE_REGEXP)).toList();
        String title = rows.get(0);
        List<String> tags = getTags(rows);

        w.setMessageId(inMess.getForwardFromMessageId());
        w.setFromChatId(inMess.getForwardFromChat().getId());
        w.setTitle(title);
        w.setTags(tags);
        w.setDescription(text);
    }

    protected List<String> getTags(List<String> rows) {
        if (rows.size() < 2) {
            return Collections.emptyList();
        }

        String tagsRow = rows.get(1);
        List<String> tags;
        int tagStartIndex = tagsRow.indexOf("#");
        if (tagStartIndex != -1) {
            tags = Arrays.stream(tagsRow.substring(tagStartIndex).split(StringUtils.SPACE))
                    .map(String::trim)
                    .filter(value -> value.startsWith("#"))
                    .map(value -> {
                        int endLetterIndex = value.length() - 1;
                        for (int i = value.length() - 1; i > 0; i--) {
                            if (Character.isLetter(value.charAt(i))) {
                                endLetterIndex = i;
                                break;
                            }
                        }
                        if (endLetterIndex != value.length() - 1) {
                            return value.substring(0, endLetterIndex + 1);
                        }
                        return value;
                    })
                    .collect(Collectors.toList());
        } else {
            tags = new ArrayList<>();
        }
        return tags;
    }

}
